package Midium;

import java.util.ArrayList;
import java.util.List;

//46.全排列
public class Solution46 {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> resList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        __permute(list, nums, 0,resList);
        return resList;
    }

    //固定一个数，递归的排列后面的数
    public void __permute(List<Integer> list, int[] nums, int index,List<List<Integer>> resList) {
        for (int i = index; i < nums.length; i++) {
            //nums[i]交换顺序到第一个位置,index为起始位置
            int temp = nums[i];
            nums[i]=nums[index];
            nums[index]=temp;
            list.add(nums[index]);
            if(list.size()==nums.length){
                resList.add(new ArrayList<>(list));
            }
            __permute(list,nums,index+1,resList);
            //用完以后先换回来，再去掉
            temp = nums[i];
            nums[i]=nums[index];
            nums[index]=temp;
            list.remove(list.size()-1);
        }
    }

    public static void main(String[] args) {
        Solution46 s46 = new Solution46();
        List<List<Integer>> permute = s46.permute(new int[]{1, 2, 3});
        for(List<Integer> list : permute){
            System.out.print("[");
            for(int a:list){
                System.out.print(a+",");
            }
            System.out.println("]");
        }
    }
}
